package cn.bitkit.tools.net;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.InputStream;
import java.io.OutputStream;

/**
 * 
 * @author changbo
 *
 */
@Slf4j
public class FtpHelper {
	
    private FTPClient ftp;
    
    private FtpHelper(){
    }

    public static FtpHelper getFtpHelper(){
    	return new FtpHelper();
    }

    public FtpHelper connect(String ip, String username, String password){
    	return connect(ip, 21, username, password);
    }

	@SneakyThrows
    public FtpHelper connect(String ip, int port, String username, String password){
		ftp = new FTPClient();
		ftp.connect(ip, port);
		ftp.login(username, password);
		ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
		if(!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
			ftp.disconnect();
		}
    	return this;
    }

	@SneakyThrows
    public FtpHelper cd(String dir){
		ftp.changeWorkingDirectory(dir);
    	return this;
    }

	@SneakyThrows
    public FtpHelper mkdir(String dir){
		ftp.makeDirectory(dir);
		return this;
    }

	@SneakyThrows
    public FtpHelper upload(InputStream inputStream, String fileName){
    	ftp.storeFile(fileName, inputStream);
    	return this;
    }

	@SneakyThrows
    public FtpHelper download(String fileName , OutputStream outputStream){
		ftp.retrieveFile(fileName, outputStream);
		return this;
    }

	@SneakyThrows
    public void disconnect(){
		if(ftp != null && ftp.isConnected()){
			ftp.logout();
			ftp.disconnect();
		}
    }
    
} 
